import { createSlice } from "@reduxjs/toolkit";
import { removeToken, request } from "@/utils/index";
import { setToken as _setToken, getToken } from "@/utils/index";
import { loginApi, getProfileApi } from "@/apis/user";

const loginStore = createSlice({
  name: 'user',
  initialState:{
    // 先从本地取，取不到再初始化
    token: getToken() || '',
    userInfo: {}
  },
  // 同步处理方法
  reducers: {
    setToken (state,action) {
      state.token = action.payload
      // 存一份到本地
      _setToken(action.payload)
    },
    setUserInfo (state,action) {
      state.userInfo = action.payload
    },
    // 清除个人信息
    clearUserInfo (state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  }
})

const {setToken, setUserInfo, clearUserInfo} = loginStore.actions;
// 请求登录，异步请求
const fetchUser = (loginForm) => {
  return async (dispatch) => {
    // 发送异步请求
    const res = await loginApi(loginForm)
    // 提交同步action 进行token的存入
    dispatch(setToken(res.data.token))
  }
}

// 获取用户个人信息的异步
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getProfileApi()
    dispatch(setUserInfo(res.data))
  }
}

const userReducer = loginStore.reducer;
// 按需导出处理方法
export {setToken, fetchUserInfo, fetchUser, clearUserInfo};
// 默认导出
export default userReducer;